<template>  
  <div class="product-management">  
    <!-- 搜索和操作区域 -->  
    <el-card class="box-card operation-container" shadow="never">  
      <el-row type="flex" justify="space-between" align="middle">  
        <el-col :span="20">  
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">  
            <el-form-item label="商品名称">  
              <el-input 
                v-model="searchForm.productName" 
                placeholder="输入商品名称"
                clearable
                @keyup.enter="onSearch"
                @clear="handleReset">
              </el-input>  
            </el-form-item>
            <el-form-item label="商品类别">
              <el-select 
                v-model="searchForm.categoryId" 
                placeholder="请选择类别"
                clearable
                style="width: 150px;">
                <el-option
                  v-for="item in categoryList"
                  :key="item.categoryId"
                  :label="item.categoryName"
                  :value="item.categoryId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>  
              <el-button type="primary" @click="onSearch" :loading="loading">  
                <el-icon><Search /></el-icon> 查询  
              </el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>  
          </el-form>  
        </el-col>  
        <el-col :span="4" style="text-align: right;">  
          <el-button type="warning" @click="addProduct">  
            <el-icon><Plus /></el-icon> 添加商品  
          </el-button>  
        </el-col>  
      </el-row>  
    </el-card>  

    <!-- 表格区域 -->  
    <el-card class="box-card table-container" shadow="never">  
      <el-table :data="tableData" style="width: 100%" border v-loading="loading">  
        <el-table-column prop="productId" label="ID" width="80" align="center" />  
        <el-table-column label="商品名称" min-width="150" align="center">  
          <template #default="scope">  
            <el-link type="primary">{{ scope.row.productName }}</el-link>  
          </template>  
        </el-table-column>  
        <el-table-column prop="categoryId" label="商品类别" width="120" align="center">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>  
        <el-table-column prop="model" label="商品型号" width="120" align="center" />  
        <el-table-column prop="color" label="商品颜色" width="100" align="center" />  
        <el-table-column prop="price" label="商品价格" width="120" align="center">
          <template #default="scope">
            ￥{{ scope.row.price }}
          </template>
        </el-table-column>  
        <el-table-column prop="quantity" label="商品数量" width="100" align="center" />
        <el-table-column label="图片" width="100" align="center">  
          <template #default="scope">  
            <el-image   
              style="width: 60px; height: 60px"  
              :src="scope.row.image || '/api/placeholder/60/60'"   
              :preview-src-list="[scope.row.image || '/api/placeholder/60/60']"  
              fit="cover"   
            />  
          </template>  
        </el-table-column>  
        <el-table-column label="操作" width="150" fixed="right" align="center">  
          <template #default="scope">  
            <el-button type="primary" :icon="Edit" @click="handleEdit(scope.row)" circle />  
            <el-button type="danger" :icon="Delete" @click="handleDelete(scope.row)" circle />  
          </template>  
        </el-table-column>  
      </el-table>  
      
      <!-- 分页区域 -->  
      <div class="pagination-container">  
        <span>第{{ queryParams.page }}页/共{{ total }}条记录</span>  
        <el-pagination  
          background  
          layout="prev, pager, next, sizes"
          :page-sizes="[5,10,15,20]"
          :total="total"
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          class="ml-auto"  
        />  
      </div>  
    </el-card>

    <!-- 添加/编辑商品弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="700px" 
      @close="resetForm"
      :close-on-click-modal="false">
      
      <el-form 
        :model="productForm" 
        :rules="productRules" 
        ref="productFormRef" 
        label-width="100px">
        
        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="productForm.productName"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="商品类别" prop="categoryId">
          <el-select 
            v-model="productForm.categoryId" 
            placeholder="请选择商品类别"
            style="width: 100%;">
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品型号" prop="model">
              <el-input
                v-model="productForm.model"
                placeholder="请输入商品型号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品颜色" prop="color">
              <el-input
                v-model="productForm.color"
                placeholder="请输入商品颜色"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品价格" prop="price">
              <el-input-number
                v-model="productForm.price"
                :min="0.01"
                :precision="2"
                :step="1"
                placeholder="请输入商品价格"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品数量" prop="quantity">
              <el-input-number
                v-model="productForm.quantity"
                :min="0"
                placeholder="请输入商品数量"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品图片" prop="image">
          <el-input
            v-model="productForm.image"
            placeholder="请输入图片URL"
          />
          <div style="margin-top: 10px;" v-if="productForm.image">
            <el-image 
              style="width: 100px; height: 100px"
              :src="productForm.image"
              fit="cover"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitLoading">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>  
</template>  

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';  
import { ElMessage, ElMessageBox } from 'element-plus';  
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue';  
import request from '../../util/request.js'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const categoryList = ref([])
const total = ref(0)

// 搜索表单
const searchForm = reactive({  
  productName: '',
  categoryId: ''
});

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10
})

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const productFormRef = ref(null)

// 商品表单
const productForm = reactive({
  productId: null,
  productName: '',
  categoryId: null,
  model: '',
  color: '',
  price: 0,
  quantity: 0,
  image: ''
})

// 表单验证规则
const productRules = reactive({
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品类别', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '数量不能小于0', trigger: 'blur' }
  ]
})

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑商品' : '添加商品'
})

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryList.value.find(item => item.categoryId === categoryId)
  return category ? category.categoryName : '未知分类'
}

// 获取商品列表
const fetchProductList = async () => {
  loading.value = true
  try {
    const params = {
      page: queryParams.page,
      pageSize: queryParams.pageSize,
      productName: searchForm.productName || null,
      categoryId: searchForm.categoryId || null
    }
    
    console.log('请求参数:', params)
    
    const response = await request.get('/admin/product/list', { params })
    console.log('商品列表响应:', response)
    
    if (response.data && response.data.code === 1) {
      tableData.value = response.data.data.records || []
      total.value = response.data.data.total || 0
    } else {
      ElMessage.error(response.data?.msg || '数据加载失败')
    }
  } catch (error) {
    console.error('获取商品列表时出错:', error)
    ElMessage.error('网络连接失败或服务器错误')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await request.get('/admin/categories/list')
    if (response.data && response.data.code === 1) {
      categoryList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 搜索
const onSearch = () => {
  queryParams.page = 1
  fetchProductList()
}

// 重置搜索
const handleReset = () => {
  searchForm.productName = ''
  searchForm.categoryId = ''
  queryParams.page = 1
  fetchProductList()
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.page = page
  fetchProductList()
}

// 每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.page = 1
  fetchProductList()
}

// 添加商品
const addProduct = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑商品
const handleEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(productForm, {
    productId: row.productId,
    productName: row.productName,
    categoryId: row.categoryId,
    model: row.model,
    color: row.color,
    price: row.price,
    quantity: row.quantity,
    image: row.image
  })
}

// 提交（新增 / 更新）商品
const submitForm = () => {
  if (!productFormRef.value) return

  productFormRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    try {
      let res
      if (isEdit.value) {
        // 编辑
        res = await request.put('/admin/product/update', productForm)
      } else {
        // 新增（不传 productId）
        const { productId, ...addData } = productForm
        res = await request.post('/admin/product/add', addData)
      }

      const { data } = res
      if (data && data.code === 1) {
        ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
        dialogVisible.value = false
        fetchProductList()
      } else {
        ElMessage.error(data?.msg || '操作失败')
      }
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('网络或服务器错误，操作失败')
    } finally {
      submitLoading.value = false
    }
  })
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategoryList()
  fetchProductList()
})

</script>
<style scoped>  
.category-management {  
  padding: 20px;  
}  

.operation-container.el-card {  
  margin-bottom: 20px;  
}  

.el-form-item {  
  margin-bottom: 0;  
}  

.pagination-container {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  margin-top: 20px;  
}  

.ml-auto {  
  margin-left: auto;  
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 按钮样式 */
:deep(.el-button--primary) {
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-1px);
}

:deep(.el-button--warning) {
  transition: all 0.3s ease;
}

:deep(.el-button--warning:hover) {
  transform: translateY(-1px);
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 12px;
}

/* 输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 分页样式 */
:deep(.el-pagination) {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-management {
    padding: 10px;
  }
  
  :deep(.el-col) {
    margin-bottom: 10px;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 10px;
  }
  
  .ml-auto {
    margin-left: 0;
  }
}
</style>